package com.yimixian.app.fragment;

import com.ta.utdid2.android.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.ShowAdSelectChange;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.activity.BaseNaviFragmentGroupActivity;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.common.UMengConstants;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.KV;
import com.yimixian.app.model.SessionDataBean;
import com.yimixian.app.rest.api.SessionDataAPI;
import com.yimixian.app.ui.BaseHttpFragment;
import com.yimixian.app.ui.LoadingPage;
import com.yimixian.app.ui.PagerSlidingTabStrip;
import com.yimixian.app.util.DateUtil;
import com.yimixian.app.util.ServiceUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.UiUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import retrofit.client.Response;

public class SessionActivityFragment extends BaseHttpFragment implements ServiceUtils.CountDownDataListener{

    String id;
    FrameLayout mMainFrame;
    ImageButton leftBack;
    BaseNaviFragmentGroupActivity mActivity;
    FrameLayout loading_fragment;
    TextView cannotDeliverText;
    private PagerSlidingTabStrip tabs;
    private ViewPager mViewPager;
    public BaseFragment[] mFragments;
    private int mCurrentPos;
    private List<KV> mChildCategoryList = new ArrayList<>();
    private SessionDataAPI mSessionDataAPI;
    private SessionDataBean sessionDataBean;
    SortDetailPagerAdapter adapter;
    boolean isClear = false;

   
    
    public SessionActivityFragment(){
         
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (BaseNaviFragmentGroupActivity) context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_session, container, false);
        id = getArguments().getString(YMXMainActivity.HOME_DATA_KEY);
        if (TextUtils.isEmpty(id)){
            if (savedInstanceState!=null){
                id=savedInstanceState.getString(YMXMainActivity.HOME_DATA_KEY);
            }
        }
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().registerSticky(this);
        }
        initView(view);
        CartManager.getInstance().setCartQuantityTextView(
            ((YMXMainActivity) getActivity()).mCartDetailContent);
        return view;
    }

    protected void initView(View view) {
        loading_fragment  = (FrameLayout) view.findViewById(R.id.loading_fragment);
        loading_fragment.setVisibility(View.VISIBLE);
        cannotDeliverText = (TextView) view.findViewById(R.id.cannot_deliver_text);
        mMainFrame = (FrameLayout) view.findViewById(R.id.main_frame);
        leftBack = (ImageButton) view.findViewById(R.id.title_bar_left_btn);
        leftBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isAdded()) ((YMXMainActivity)getActivity()).hideActivityUI();
            }
        });
        tabs = (PagerSlidingTabStrip) view.findViewById(R.id.tabs);
        mViewPager = (ViewPager) view.findViewById(R.id.pager);
        mViewPager.setOffscreenPageLimit(2);
        tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                mCurrentPos = position;
                if (position < mFragments.length) {
                    if (mFragments[position] != null) {
                        if (sessionDataBean != null && sessionDataBean.specials != null &&
                                sessionDataBean.specials.size() > position) {
                            Map<String, String> hashMap = new HashMap<>();
                            hashMap.put("ID", sessionDataBean.specials.get(position).keyId);
                            DateUtil.setCityUMeng(hashMap, UMengConstants.NEW_SESSION_PV);
                            DateUtil.setCityUMeng(hashMap, UMengConstants.NEW_SESSION_CHANGESESSION);
                        }

                        cancelEventBus();
                        if (!EventBus.getDefault().isRegistered(mFragments[position])) {
                            EventBus.getDefault().registerSticky(mFragments[position]);
                        }
                        ((SessionActivityListFragment) mFragments[position]).sessionDataBean = sessionDataBean;
                        if (((SessionActivityListFragment) mFragments[position]).result
                                == LoadingPage.LoadResult.SUCCEED) {
                            mFragments[position].show();
                            ((SessionActivityListFragment) mFragments[position]).showIsTime();
                        } else {
                            mFragments[position].showLoad();
                        }

                    }
                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        fetchData(true, SessionDataAPI.SESSIONDATAURL);
    }

    void cancelEventBus(){
        for (int i = 0; i < mFragments.length; i++){
            if (EventBus.getDefault().isRegistered(mFragments[i])) {
                EventBus.getDefault().unregister(mFragments[i]);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null)
            UiUtils.updateCartDescription(getActivity(), Constants.PageType.SESSION);
    }

    @Override
    public void isNeedUpdate() {
        if (mFragments != null && mFragments.length > mCurrentPos){
            Fragment fragment = mFragments[mCurrentPos];
            if (fragment != null) {
                ((SessionActivityListFragment) fragment).isNeedUpdate();
            }
        }
    }

    @Override
    public void isNeedUnbindService() {

    }

    class SortDetailPagerAdapter extends FragmentPagerAdapter {

        public SortDetailPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mChildCategoryList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mChildCategoryList.get(position).value;
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            if (mFragments[position] == null || !(mFragments[position] instanceof BaseFragment)) {
                mFragments[position] = new SessionActivityListFragment(
                        mActivity, sessionDataBean, position, null, mMainFrame);
            }           
            if (position == mCurrentPos) {
                ((SessionActivityListFragment)mFragments[position]).show(sessionDataBean);
            }           
            return mFragments[position];
        }


        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            return super.instantiateItem(container, position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
            if (position<getChildFragmentManager().getFragments().size()) {
                FragmentTransaction trans = getChildFragmentManager().beginTransaction();
                if (object != null && EventBus.getDefault().isRegistered(object)){
                    EventBus.getDefault().unregister(object);
                }
                trans.remove((Fragment) object);
                trans.commitAllowingStateLoss();
                if (position<mFragments.length) {
                    if (mFragments[position] != null &&
                            EventBus.getDefault().isRegistered(mFragments[position]))
                        EventBus.getDefault().unregister(mFragments[position]);
                    mFragments[position] = null;
                }
            }
        }
    }

    @Override
    public void initRequestAPI(String requestKeys) {
        Address address = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if (isClear) id = "";
        if (address != null && !StringUtils.isEmpty(address.storeId)){
            mSessionDataAPI = new SessionDataAPI(address.storeId,
                    StringUtils.isEmpty(id) ? "" : id, this);
            mSessionDataAPI.getSessionData();
        }
    }
    @Override
    public void fetchDataFromNetwork(String key) {
        initRequestAPI(key);
    }
    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        loading_fragment.setVisibility(View.GONE);
        if (url.contains(SessionDataAPI.SESSIONDATAURL) && mSessionDataAPI != null){
            sessionDataBean = mSessionDataAPI.parseJson(responseJson);
            initData(sessionDataBean);
            UiUtils.updateCartDescription(getActivity(), Constants.PageType.SESSION);
        }
    }

    @Override
    public void getRawResponse(String url, Response response) {
        super.getRawResponse(url, response);
        ServiceUtils.setTime(response);
    }

    void initData(SessionDataBean sessionDataBean){
        //slides个数
        if (sessionDataBean != null && !StringUtils.isEmpty(sessionDataBean.cannotDeliverText)){
            mChildCategoryList = new ArrayList<>();
            adapter = new SortDetailPagerAdapter(getChildFragmentManager());
            mViewPager.setAdapter(adapter);
            tabs.setViewPager(mViewPager);
            cannotDeliverText.setVisibility(View.VISIBLE);
            cannotDeliverText.setText(sessionDataBean.cannotDeliverText);
            return;
        }
        cannotDeliverText.setVisibility(View.GONE);

        if (sessionDataBean.specials == null || sessionDataBean.specials.size() == 0) return;
        mFragments = new BaseFragment[sessionDataBean.specials.size()];
        //默认选中
        if (!StringUtils.isEmpty(sessionDataBean.specialId)){
            mChildCategoryList = sessionDataBean.specials;
            for (int i = 0; i < mChildCategoryList.size(); i++){
                String keyId = mChildCategoryList.get(i).keyId;
                if (!StringUtils.isEmpty(keyId) &&
                        !StringUtils.isEmpty(sessionDataBean.specialId) &&
                        keyId.equals(sessionDataBean.specialId)){
                    mCurrentPos = i;
                    break;
                }
            }
        }
        adapter = new SortDetailPagerAdapter(getChildFragmentManager());
        mViewPager.setAdapter(adapter);
        tabs.setViewPager(mViewPager);
        isClear = false;
        mViewPager.setCurrentItem(mCurrentPos);
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage, boolean errorFromUs) {
        loading_fragment.setVisibility(View.GONE);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString(YMXMainActivity.HOME_DATA_KEY,id);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
        List<Fragment> fragments = getChildFragmentManager().getFragments();
        if (fragments != null){
            for (int i = 0; i < fragments.size(); i++){
                if (EventBus.getDefault().isRegistered(fragments.get(i))) {
                    EventBus.getDefault().unregister(fragments.get(i));
                }
            }
            getChildFragmentManager().getFragments().clear();
        }
        super.onDestroy();
    }

    // 地址管理页面 监听到地址改变更新首页内容
    public void onEventMainThread(ShowAdSelectChange event) {
//        isClear = true;
//        fetchData(true, SessionDataAPI.SESSIONDATAURL);
        EventBus.getDefault().removeStickyEvent(event);
        if (isAdded()) ((YMXMainActivity)mActivity).hideActivityUINoAnimation();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
